package com.cg.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.cg.advice.ApiResult;
import com.cg.entity.WeChatUser;
import com.cg.utils.WechatUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequiredArgsConstructor
public class WeCharController {

    private final RedisTemplate<String, String> redisTemplate;

    private static final String QR_CODE_EXPIRE_KEY = "QrCode:EXPIRE_";

    /**
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @return
     */
    @GetMapping("/wxCheck")
    public String wxSignatureCheck(@RequestParam(value = "signature") String signature,
                                   @RequestParam(value = "timestamp") String timestamp,
                                   @RequestParam(value = "nonce") String nonce,
                                   @RequestParam(value = "echostr") String echostr) {
        log.info("收到微信校验请求,echostr:{}", echostr);

        return echostr;
    }

    /**
     * 登录二维码跳转获取授权码
     *
     * @param response
     * @throws IOException
     */
    @GetMapping("/wxLogin")
    @ResponseBody
    public void wxLoginPage(HttpServletResponse response) throws IOException {
        //redirect_uri是回调的地址 注意要转成Url Encode格式
        String redirectUtl = URLEncoder.encode("https://eb09982.r1.cpolar.top/wxCallback", StandardCharsets.UTF_8);
        //微信appId
        String appId = WechatUtil.APP_ID;
        //构造二维码链接地址
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" +
                redirectUtl + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        //生成二维码，扫描后跳转到指定地址
        response.setContentType("image/png");

        QrCodeUtil.generate(url, 300, 300, "jpg", response.getOutputStream());
        //设置过期时间
        redisTemplate.opsForValue().setIfAbsent(QR_CODE_EXPIRE_KEY + appId, appId, 10, TimeUnit.SECONDS);
    }

    @RequestMapping("/wxCallback")
    public ApiResult<WeChatUser> pcCallback(String code, String state, HttpServletRequest httpServletRequest, HttpServletResponse response, HttpSession httpSession) throws IOException {

        Optional.ofNullable(redisTemplate.opsForValue().get(QR_CODE_EXPIRE_KEY + WechatUtil.APP_ID))
                .orElseThrow(() -> new RuntimeException("二维码已过期"));
        WeChatUser userInfo = WechatUtil.getUserInfo(code);
        return ApiResult.success(userInfo);
    }

}
